package com.zy.explore.sys.infrastructure.schedule;

import com.zy.explore.sys.application.service.DingTalkService;
import com.zy.explore.sys.application.service.SysUserService;
import com.zy.explore.sys.domain.mybatis.entity.SysUser;
import com.zy.explore.sys.infrastructure.constant.DingTalkResource;
import com.zy.explore.sys.infrastructure.third.dingtalk.frm.GetUserDetailFrm;
import com.zy.explore.sys.infrastructure.third.dingtalk.vo.DingUserDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * description 状态补偿定时任务
 *
 * @author 🇨🇳中国印🇨🇳
 * @date 2021年07月11日 18:19
 */
@Slf4j
@EnableScheduling
@Component
public class StateCompensationSchedule {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private DingTalkService dingTalkService;

    /**
     * 每整点查询到钉钉查询一次当前的用户是否存在，不存在则修改为已离职状态
     */
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void syncDingUserStatus() {
        log.info("schedule:同步钉钉用户状态开始");
        List<SysUser> userList = sysUserService.getUserList();
        if (CollectionUtils.isEmpty(userList)) {
            return;
        }
        for (SysUser user : userList) {
            try {
                DingUserDetailVO userDetail = dingTalkService.getDingUserDetail(GetUserDetailFrm.builder().userid(user.getDtUserId()).build());
                if (userDetail != null && userDetail.getErrcode() == DingTalkResource.DD_OK) {
                    if (!StringUtils.isEmpty(userDetail.getUserid())) {
                        // 如果本系统的用户在钉钉中找得到userId且在职状态为 false:已离职，则更新状态为true:在职
                        if (!user.getLeaveStatus()) {
                            user.setLeaveStatus(true);
                        }
                    } else {
                        // 如果本系统的而用户在钉钉中找不到且在职状态为true:在职，则更新状态为false:已离职
                        if (user.getLeaveStatus()) {
                            user.setLeaveStatus(false);
                            user.setLeaveDate(new Date());
                        }
                    }
                    sysUserService.updateByIdSelective(user);
                } else {
                    log.info("schedule:调用钉钉查询用户详情返回错误，错误码：{} 错误提示信息：{}", userDetail.getErrcode(), userDetail.getErrmsg());
                    // 如果本系统的用户在钉钉中找不到且在职状态为true:在职，则更新状态为false:已离职
                    if (user.getLeaveStatus()) {
                        user.setLeaveStatus(false);
                        sysUserService.updateByIdSelective(user);
                    }
                }
            } catch (Exception e) {
                log.error("schedule:调用钉钉查询用户详情接口异常:", e);
            }
        }
        log.info("schedule:同步钉钉用户状态结束");
    }
}
